package com.jmda.platform.engine.form.component.form.imp;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jmda.platform.engine.form.component.form.FormUIComponentAbst;
import org.springframework.stereotype.Service;
import org.springframework.ui.ModelMap;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service("UI_FORM_日期")
public class FormUIComponentDateImp extends FormUIComponentAbst {

	@Override
	public String getHtmlDefine(String params) {
		// TODO Auto-generated method stub
		FormUIComponentDataParamsModel paramModel = buildFormUIComponentTextParamsModel(params);
		String isNotNull = "";
		if (!super.getFormMetadataMapModel().isIs_null()) {
			isNotNull = "data-options=required:true";
		}
		Object value =  super.getValue();
		if(value ==null||value.equals("")){
			value = "";
		}else{
			 SimpleDateFormat datetimeFormat = new SimpleDateFormat("yyyy-MM-dd");
			 value = datetimeFormat.format(new Date((Long)value));
		}
		String html2="<input type='text' class='form-control easyui-datebox' " +isNotNull+" "+ (paramModel.getExtendedCode().trim().length() == 0 ? "" : paramModel.getExtendedCode()) + " name=\"" + super.getFormMetadataMapModel().getColumn_lable() + "\" value='" + value+ "'>";
		return html2;
	}

	@Override
	public String getParamSetingWeb(String params, HttpServletRequest request, ModelMap map) {
		// TODO Auto-generated method stub
		FormUIComponentDataParamsModel paramModel = buildFormUIComponentTextParamsModel(params);
		map.put("extendedCode", paramModel.getExtendedCode());
		return "repository/form/ui/Sys_Resonsitory_Form_UI_Date";
	}

	private FormUIComponentDataParamsModel buildFormUIComponentTextParamsModel(String params) {
		ObjectMapper mapper = new ObjectMapper();
		FormUIComponentDataParamsModel paramModel = null;
		if (params != null && params.trim().length() > 0) {
			try {
				paramModel = mapper.readValue(params, FormUIComponentDataParamsModel.class);
			} catch (JsonParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (JsonMappingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		paramModel = paramModel == null ? new FormUIComponentDataParamsModel() : paramModel;
		return paramModel;
	}
}

class FormUIComponentDataParamsModel {
	private String extendedCode = "";



	public String getExtendedCode() {
		return extendedCode;
	}

	public void setExtendedCode(String extendedCode) {
		this.extendedCode = extendedCode;
	}

}
